<template>
  <v-container class="fill-height">
    <v-row align="center" justify="center">
      <v-col cols="12" sm="8" md="6">
        <v-card class="elevation-12">
          <v-card-title class="headline text-center pa-6">
            图片诗歌生成器
          </v-card-title>
          <v-card-text>
            <v-file-input
              v-model="file"
              label="选择图片"
              prepend-icon="mdi-camera"
              accept="image/*"
              :rules="[(v) => !!v || '请选择一张图片']"
            ></v-file-input>
            <v-btn
              @click="generatePoetry"
              :loading="isLoading"
              :disabled="!file"
              color="primary"
              block
              class="mt-4"
            >
              生成诗歌
            </v-btn>
          </v-card-text>
          <v-card-text v-if="poem" class="text-center">
            <v-divider class="my-4"></v-divider>
            <h3 class="subtitle-1 font-weight-bold mb-2">生成的诗歌：</h3>
            <p class="body-1" style="white-space: pre-line">{{ poem }}</p>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup>
import { ref } from 'vue';
// import { generatePoetryFromImage } from '@/services/poetryService';

const file = ref(null);
const isLoading = ref(false);
const poem = ref('');

async function generatePoetry() {
  if (!file.value) {
    console.error('请先选择图片');
    return;
  }

  isLoading.value = true;
  poem.value = '';

  try {
    const base64String = await readFileAsBase64(file.value);
    const generatedPoem = await generatePoetryFromImage(base64String);
    poem.value = generatedPoem;
  } catch (error) {
    console.error('生成诗歌失败:', error);
  } finally {
    isLoading.value = false;
  }
}

async function generatePoetryFromImage(base64String) {
  const API_KEY =
    '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';
  try {
    const response = await fetch(
      'https://openrouter.ai/api/v1/chat/completions',
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: 'qwen/qwen-2-vl-7b-instruct:free',
          messages: [
            {
              role: 'user',
              content: [
                {
                  type: 'text',
                  text: '请根据给出的图片，作一首七言绝句诗',
                },
                {
                  type: 'image_url',
                  image_url: {
                    url: `data:image/jpeg;base64,${base64String}`,
                  },
                },
              ],
            },
          ],
        }),
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    if (data.choices && data.choices.length > 0) {
      return data.choices[0].message.content;
    } else {
      throw new Error('未能生成诗歌');
    }
  } catch (error) {
    console.error('API 调用失败:', error);
    throw error;
  }
}
function readFileAsBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result.split(',')[1]);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}
</script>

<style scoped>
.v-card {
  max-width: 500px;
  margin: auto;
}
</style>
